/*
 * Copyright 2015-2019 Evun Technology. 
 * 
 * This software is the confidential and proprietary information of
 * Evun Technology. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with evun.cn.
 */
package cn.evun.sweet.demo.services;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.ThreadContext;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;

import cn.evun.sweet.common.util.Assert;
import cn.evun.sweet.common.util.StringUtils;
import cn.evun.sweet.common.ws.soap.SOAPClient;
import cn.evun.sweet.core.cache.CacheAccessor;
import cn.evun.sweet.core.cache.CacheRequired;
import cn.evun.sweet.core.common.R;
import cn.evun.sweet.core.exception.SweetException;
import cn.evun.sweet.core.log.MDCLogger;
import cn.evun.sweet.core.mybatis.page.Page;
import cn.evun.sweet.core.mybatis.page.PageHelper;
import cn.evun.sweet.core.service.RegistyMethod;
import cn.evun.sweet.core.service.RegistyService;
import cn.evun.sweet.demo.dao.OrgMapper;
import cn.evun.sweet.demo.model.OrgDo;

/**
 * 后端演示功能的服务层代码
 *
 * @author yangw
 * @since 1.0.0
 */
@RegistyService
@CacheRequired
@CacheConfig(cacheNames={R.cache.cache_region_main})  
public class MainService {
	
	protected static final Logger LOGGER = LogManager.getLogger();	

	@Resource
	private OrgMapper orgMapper;
	
	public String contact_catche_key = "contact_catche";
	
	/**
	 * 查询组织列表，并同时关联查询出所属企业信息及组织下属的人员列表
	 */
	public Page<OrgDo> queryOrgPage(Long tenantId, Integer pageNum){
		Assert.notNull(tenantId, "tenantid must not be null!");
		PageHelper.startPage(pageNum, 5);
		//Page<OrgDo> result = (Page<OrgDo>)orgMapper.selectOrgsByTenant(tenantId);
		Page<OrgDo> result = (Page<OrgDo>)orgMapper.selectOrgList(tenantId);
		return result;
	}
	
	/**
	 * 从缓存中获取所有通讯录用户列表
	 */
	@SuppressWarnings("unchecked")
	@Cacheable(key = "#root.target.contact_catche_key")//如果没有则创建一个到缓存中，否则直接读取缓存中的资源
	public List<Map<String, String>> queryUserByCache(){
		/*通过直接操作缓存来模拟数据库查询过程*/
		List<Map<String, String>> userlist = (List<Map<String, String>>)CacheAccessor.doGet("contacts_inituser");
		if(userlist == null){ //相当于初始化数据库
			userlist = getInitUsersForCache();
			CacheAccessor.doPut("contacts_inituser", userlist); //通过直接操作缓存来模拟数据库查询过程
		}
		return userlist;
	}
	
	/**
	 * 更新用户信息，并同步到缓存中
	 */
	@SuppressWarnings("unchecked")
	@CachePut(key = "#root.target.contact_catche_key")
	public List<Map<String, String>> saveUserByCache(Map<String, String> user){
		/*模拟将user持久化到DB中的过程*/
		List<Map<String, String>> userlist = (List<Map<String, String>>)CacheAccessor.doGet("contacts_inituser");
		for(Map<String, String> usermap : userlist){
			if(usermap.get("name").equalsIgnoreCase(user.get("name"))){
				userlist.remove(usermap);
				break;
			}
		}
		userlist.add(user);
		return userlist;
	}
	
	
	/**
	 * 删除用户信息，并同步到缓存中
	 */
	@SuppressWarnings("unchecked")
	@CachePut(key = "#root.target.contact_catche_key")
	public List<Map<String, String>> delUserByCache(String name){
		Assert.notNull(name, "Contact name must not be null.");
		/*模拟将user从DB中删除的过程*/
		List<Map<String, String>> userlist = (List<Map<String, String>>)CacheAccessor.doGet("contacts_inituser");
		for(Map<String, String> usermap : userlist){
			if(usermap.get("name").equalsIgnoreCase(name)){
				userlist.remove(usermap);
				break;
			}
		}
		return userlist;
	}
	
	/**
	 * 产生一些日志用于前台演示
	 */
	@RegistyMethod("standard.createlog")
	public void createLog(){		
		LOGGER.warn(R.log.log_marker_rewrite, "Personal bank count 62226 7687 1376 6777 hrefer to the service of effective cash "
				+ "and investment management by associating the customer's current savings deposit with low-risk funds such as "
				+ "the money market and short-term debts ");
		MDCLogger logger = new MDCLogger();
		logger.setMessage("this recorde will show you how to user MDC logs.", ThreadContext.getContext());
		orgMapper.selectOrgsByTenant(10000L);
		throw new SweetException("This exception just to show the log push message displayed.");		
	}
	
	/**
	 * 根据城市名称查询当前天气信息
	 */
	public Map<String, String> getCityWeather(String cityName, String countryName){		
		Assert.hasLength(cityName, "City name must not be null.");
		SOAPClient soapCilent = new SOAPClient();
		soapCilent.setDestinationURL("http://www.webservicex.net/globalweather.asmx");
		LinkedHashMap<String,Object> params = new LinkedHashMap<String,Object>();
		params.put("CityName", cityName);
		params.put("CountryName", countryName==null?"":countryName);
		LinkedHashMap<String, String> xsdmap = new LinkedHashMap<String, String>();
		xsdmap.put("web", "http://www.webserviceX.NET");
		String res = soapCilent.execute("GetWeather", params, xsdmap, "http://www.webserviceX.NET/GetWeather");
		if(StringUtils.hasText(res)){
			Map<String, String> result = new HashMap<String, String>();
			result.put("Wind", parseWeatherValue(res,"Wind"));
			result.put("Visibility", parseWeatherValue(res,"Visibility"));			
			result.put("Temperature", parseWeatherValue(res,"Temperature"));
			result.put("DewPoint", parseWeatherValue(res,"DewPoint"));
			result.put("RelativeHumidity", parseWeatherValue(res,"RelativeHumidity"));
			try{
				result.put("SkyConditions", parseWeatherValue(res,"SkyConditions"));
			}catch(Exception e){				
			}
			return result;
		}
		return null;
	}
	
	/**
	 * 模拟从数据库查询到所有的用户信息
	 */
	private List<Map<String, String>> getInitUsersForCache(){
		List<Map<String, String>> userlist = new ArrayList<Map<String, String>>(20);
		Map<String, String> user1 = new HashMap<String, String>(8);
		user1.put("group", "杭州测试科技有限公司");
		user1.put("name", "杨威");
		user1.put("mobile", "13812340000");
		user1.put("work", "(021) 1234 8755");
		user1.put("home", "(021) 9000 9877");
		user1.put("notes", "走自己的路，让别人无路可走！");
		user1.put("address", "杭州滨江区江陵路1760号");
		user1.put("email", "yangw@email.com");
		userlist.add(user1);
		Map<String, String> user2 = new HashMap<String, String>(8);
		user2.put("group", "杭州测试科技有限公司");
		user2.put("name", "管理员");
		user2.put("mobile", "13812340001");
		user2.put("work", "(021) 1234 8755");
		user2.put("home", "(021) 9000 9877");
		user2.put("notes", "走自己的路，让别人无路可走！");
		user2.put("address", "杭州滨江区江陵路1760号");
		user2.put("email", "admin@email.com");
		userlist.add(user2);
		Map<String, String> user3 = new HashMap<String, String>(8);
		user3.put("group", "呼叫中心");
		user3.put("name", "周文广");
		user3.put("mobile", "13812340002");
		user3.put("work", "(021) 1234 8755");
		user3.put("home", "(021) 9000 9877");
		user3.put("notes", "走自己的路，让别人无路可走！");
		user3.put("address", "杭州滨江区江陵路1760号");
		user3.put("email", "zhouwg@email.com");
		userlist.add(user3);
		Map<String, String> user4 = new HashMap<String, String>(8);
		user4.put("group", "呼叫中心");
		user4.put("name", "周航波");
		user4.put("mobile", "13812340003");
		user4.put("work", "(021) 1234 8755");
		user4.put("home", "(021) 9000 9877");
		user4.put("notes", "走自己的路，让别人无路可走！");
		user4.put("address", "杭州滨江区江陵路1760号");
		user4.put("email", "zhouhb@email.com");
		userlist.add(user4);
		Map<String, String> user5 = new HashMap<String, String>(8);
		user5.put("group", "呼叫中心");
		user5.put("name", "顾巍");
		user5.put("mobile", "13812340004");
		user5.put("work", "(021) 1234 8755");
		user5.put("home", "(021) 9000 9877");
		user5.put("notes", "走自己的路，让别人无路可走！");
		user5.put("address", "杭州滨江区江陵路1760号");
		user5.put("email", "guw@email.com");
		userlist.add(user5);
		Map<String, String> user6 = new HashMap<String, String>(8);
		user6.put("group", "技术研发中心");
		user6.put("name", "林佳航");
		user6.put("mobile", "13812340005");
		user6.put("work", "(021) 1234 8755");
		user6.put("home", "(021) 9000 9877");
		user6.put("notes", "走自己的路，让别人无路可走！");
		user6.put("address", "杭州滨江区江陵路1760号");
		user6.put("email", "linjh@email.com");
		userlist.add(user6);
		Map<String, String> user7 = new HashMap<String, String>(8);
		user7.put("group", "技术研发中心");
		user7.put("name", "王黎");
		user7.put("mobile", "13812340006");
		user7.put("work", "(021) 1234 8755");
		user7.put("home", "(021) 9000 9877");
		user7.put("notes", "走自己的路，让别人无路可走！");
		user7.put("address", "杭州滨江区江陵路1760号");
		user7.put("email", "wangl@email.com");
		userlist.add(user7);
		Map<String, String> user8 = new HashMap<String, String>(8);
		user8.put("group", "技术研发中心");
		user8.put("name", "姚旭");
		user8.put("mobile", "13812340007");
		user8.put("work", "(021) 1234 8755");
		user8.put("home", "(021) 9000 9877");
		user8.put("notes", "走自己的路，让别人无路可走！");
		user8.put("address", "杭州滨江区江陵路1760号");
		user8.put("email", "yaox@email.com");
		userlist.add(user8);
		Map<String, String> user9 = new HashMap<String, String>(8);
		user9.put("group", "技术研发中心");
		user9.put("name", "张辽");
		user9.put("mobile", "13812340008");
		user9.put("work", "(021) 1234 8755");
		user9.put("home", "(021) 9000 9877");
		user9.put("notes", "走自己的路，让别人无路可走！");
		user9.put("address", "杭州滨江区江陵路1760号");
		user9.put("email", "zhangl@email.com");
		userlist.add(user9);
		Map<String, String> user10 = new HashMap<String, String>(8);
		user10.put("group", "销售运营中心");
		user10.put("name", "海瑟薇");
		user10.put("mobile", "13812340009");
		user10.put("work", "(021) 1234 8755");
		user10.put("home", "(021) 9000 9877");
		user10.put("notes", "走自己的路，让别人无路可走！");
		user10.put("address", "杭州滨江区江陵路1760号");
		user10.put("email", "hasisw@email.com");
		userlist.add(user10);
		Map<String, String> user11 = new HashMap<String, String>(8);
		user11.put("group", "销售运营中心");
		user11.put("name", "钱嘉乐");
		user11.put("mobile", "13812340010");
		user11.put("work", "(021) 1234 8755");
		user11.put("home", "(021) 9000 9877");
		user11.put("notes", "走自己的路，让别人无路可走！");
		user11.put("address", "杭州滨江区江陵路1760号");
		user11.put("email", "qianjl@email.com");
		userlist.add(user11);
		Map<String, String> user12 = new HashMap<String, String>(8);
		user12.put("group", "平台产品架构组");
		user12.put("name", "张建国");
		user12.put("mobile", "13812340011");
		user12.put("work", "(021) 1234 8755");
		user12.put("home", "(021) 9000 9877");
		user12.put("notes", "走自己的路，让别人无路可走！");
		user12.put("address", "杭州滨江区江陵路1760号");
		user12.put("email", "zhangjg@email.com");
		userlist.add(user12);
		Map<String, String> user13 = new HashMap<String, String>(8);
		user13.put("group", "业务产品组");
		user13.put("name", "李相宜");
		user13.put("mobile", "13812340012");
		user13.put("work", "(021) 1234 8755");
		user13.put("home", "(021) 9000 9877");
		user13.put("notes", "走自己的路，让别人无路可走！");
		user13.put("address", "杭州滨江区江陵路1760号");
		user13.put("email", "lixy@email.com");
		userlist.add(user13);
		Map<String, String> user14 = new HashMap<String, String>(8);
		user14.put("group", "业务产品组");
		user14.put("name", "张海");
		user14.put("mobile", "13812340013");
		user14.put("work", "(021) 1234 8755");
		user14.put("home", "(021) 9000 9877");
		user14.put("notes", "走自己的路，让别人无路可走！");
		user14.put("address", "杭州滨江区江陵路1760号");
		user14.put("email", "zhangh@email.com");
		userlist.add(user14);
		Map<String, String> user15 = new HashMap<String, String>(8);
		user15.put("group", "市场综合渠道推广部门");
		user15.put("name", "魏建军");
		user15.put("mobile", "13812340014");
		user15.put("work", "(021) 1234 8755");
		user15.put("home", "(021) 9000 9877");
		user15.put("notes", "走自己的路，让别人无路可走！");
		user15.put("address", "杭州滨江区江陵路1760号");
		user15.put("email", "weijj@email.com");
		userlist.add(user15);		
		return userlist;
	}
	
	/**
	 * 解析天气预报的数据
	 */
	private String parseWeatherValue(String source, String key){
		String[] result = StringUtils.split(source, "&lt;"+key+"&gt;");
		return StringUtils.split(result[1], "&lt;/"+key+"&gt;")[0];		
	}
	
}
